//@author A0084556W
package Database;

import java.io.File;
import java.util.Vector;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import Main.Item;


public class Database {
	
	private final String datapath = System.getProperty("user.dir") + "\\src\\Database\\";
	
	public void saveData(Vector<Item> itemList) throws Exception{
		try{
			String filepath = datapath + "data.xml";
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			
			Element rootElement = doc.createElement("itemList");
			doc.appendChild(rootElement);

			
			
			for(int i = 0; i < itemList.size(); i++){
				// element "Item" append to root element
				Element item = doc.createElement("Item");
				rootElement.appendChild(item);
                
				
				Item tempitem = itemList.elementAt(i);
				
				
				Element name = doc.createElement("name");
				name.appendChild(doc.createTextNode(tempitem.getName()));
				item.appendChild(name);
				
				Element price = doc.createElement("price");
				price.appendChild(doc.createTextNode(Double.toString(tempitem.getPrice())));
				item.appendChild(price);
				
				Element necessityValue = doc.createElement("necessityValue");
				necessityValue.appendChild(doc.createTextNode(Integer.toString(tempitem.getNecessityValue())));
				item.appendChild(necessityValue);
				
				Element date = doc.createElement("date");
				item.appendChild(date);
				
				Element day = doc.createElement("day");			
				day.appendChild(doc.createTextNode(Integer.toString(tempitem.getDate().getDay())));
				date.appendChild(day);
				
				Element month = doc.createElement("month");			
				month.appendChild(doc.createTextNode(Integer.toString(tempitem.getDate().getMonth())));
				date.appendChild(month);
				
				Element year = doc.createElement("year");			
				year.appendChild(doc.createTextNode(Integer.toString(tempitem.getDate().getYear())));
				date.appendChild(year);
				
				Element place = doc.createElement("place");
				place.appendChild(doc.createTextNode(tempitem.getPlace()));
				item.appendChild(place);
				
				Element category = doc.createElement("category");
				category.appendChild(doc.createTextNode(tempitem.getCategory()));
				item.appendChild(category);
				
				Element payment = doc.createElement("payment");
				payment.appendChild(doc.createTextNode(tempitem.getPay()));
				item.appendChild(payment);
                
                
			}

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(filepath));
			transformer.transform(source, result);

		} 	catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}
	
	public Vector <Item> readFile (){
		String filepath = datapath + "data.xml";
		Vector <Item> tempItemList = new Vector <Item>();
		
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder;
			docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(new File(filepath));
			
			Element rootElement = doc.getDocumentElement();
			rootElement.normalize();
			
			NodeList listOfEntries = doc.getElementsByTagName("Item");
			int totalEntries = listOfEntries.getLength();
			for (int i = 0; i < totalEntries; i++){
				Item tempItem = new Item();
				Node firstEntryNode = listOfEntries.item(i);
				Element firstEntryElement = (Element)firstEntryNode;
				
				NodeList nameList = firstEntryElement.getElementsByTagName("name");
				Element nameElement = (Element)nameList.item(0);
				NodeList textnameList = nameElement.getChildNodes();
				tempItem.setName(((Node)textnameList.item(0)).getNodeValue());
				
				NodeList priceList = firstEntryElement.getElementsByTagName("price");
				Element priceElement = (Element)priceList.item(0);
				NodeList textpriceList = priceElement.getChildNodes();
				tempItem.setPrice(Double.valueOf(((Node)textpriceList.item(0)).getNodeValue()));
				
				NodeList neceList = firstEntryElement.getElementsByTagName("necessityValue");
				Element neceElement = (Element)neceList.item(0);
				NodeList textneceList = neceElement.getChildNodes();
				tempItem.setNecessityValue(Integer.valueOf(((Node)textneceList.item(0)).getNodeValue()));
				
				NodeList dateList = firstEntryElement.getElementsByTagName("date");
				Element dateElement = (Element)dateList.item(0);
				
				NodeList dayList = dateElement.getElementsByTagName("day");
				Element dayElement = (Element)dayList.item(0);
				NodeList textdayList = dayElement.getChildNodes();												
				int tempDay = (Integer.valueOf(((Node)textdayList.item(0)).getNodeValue()));
				tempItem.getDate().setDay(tempDay);
				
				NodeList monthList = dateElement.getElementsByTagName("month");
				Element monthElement = (Element)monthList.item(0);
				NodeList textmonthList = monthElement.getChildNodes();												
				int tempMonth = (Integer.valueOf(((Node)textmonthList.item(0)).getNodeValue()));
				tempItem.getDate().setMonth(tempMonth);
				
				NodeList yearList = dateElement.getElementsByTagName("year");
				Element yearElement = (Element)yearList.item(0);
				NodeList textyearList = yearElement.getChildNodes();												
				int tempYear = (Integer.valueOf(((Node)textyearList.item(0)).getNodeValue()));
				tempItem.getDate().setYear(tempYear);
				
				NodeList placeList = firstEntryElement.getElementsByTagName("place");
				Element placeElement = (Element)placeList.item(0);
				NodeList textplaceList = placeElement.getChildNodes();
				tempItem.setPlace(((Node)textplaceList.item(0)).getNodeValue());
				
				NodeList categoryList = firstEntryElement.getElementsByTagName("category");
				Element categoryElement = (Element)categoryList.item(0);
				NodeList textcategoryList = categoryElement.getChildNodes();
				tempItem.setCategory(((Node)textcategoryList.item(0)).getNodeValue());
				
				NodeList paymentList = firstEntryElement.getElementsByTagName("payment");
				Element paymentElement = (Element)paymentList.item(0);
				NodeList textpaymentList = paymentElement.getChildNodes();
				tempItem.setPay(((Node)textpaymentList.item(0)).getNodeValue());
				
				tempItemList.add(tempItem);
			}
			
		
			
		} catch (SAXParseException err) {
			System.out.println ("** Parsing error" + ", line " 
					+ err.getLineNumber () + ", uri " + err.getSystemId ());
			System.out.println(" " + err.getMessage ());

		}catch (SAXException e) {
			Exception x = e.getException ();
			((x == null) ? e : x).printStackTrace ();

		}catch (Throwable t) {
			t.printStackTrace ();
		}
		
		return tempItemList;
	}
	
}
